﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Data;
using System.Data.SqlClient;

using SIPO.Library;
using SIPO.Library.DomainObject.Administration.Catalog;
using SIPO.Library.Enum;
using SIPO.Library.Interfaces;

namespace SIPO.Library.DataAccess.Administration.Catalog
{
    public partial class JobManagerialCompetencyRepo : ISearchable<JobManagerialCompetency>
    {
        public object SelectScalar(SQL.Function.Aggregate function, string column,string parameters)
        {
            object _result = null;
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    StringBuilder sbQuery = new StringBuilder();
                    switch (function)
                    {
                        case SQL.Function.Aggregate.Max:
                            sbQuery.AppendFormat("SELECT MAX({0}) FROM master.JobManagerialCompetency {1}", column,parameters);
                            break;
                        case SQL.Function.Aggregate.Min:
                            sbQuery.AppendFormat("SELECT MIN({0}) FROM master.JobManagerialCompetency {1}", column, parameters);

                            break;
                        case SQL.Function.Aggregate.Distinct:
                            sbQuery.AppendFormat("SELECT DISTINCT({0}) FROM master.JobManagerialCompetency {1}", column, parameters);
                            break;
                        case SQL.Function.Aggregate.Count:
                            sbQuery.AppendFormat("SELECT COUNT(A.POSITIONID) FROM (");
                            sbQuery.AppendFormat(@"SELECT DISTINCT A.POSITIONID FROM master.JobManagerialCompetency A INNER JOIN master.Competency B ON A.CompetencyID = B.ComptID INNER JOIN master.Position C ON A.PositionID = C.PositionID INNER JOIN master.LevelCompetency D ON A.LevelCompetencyID = D.ID  {1} ", column, parameters);
                            sbQuery.AppendFormat(") A");
                            break;
                        case SQL.Function.Aggregate.Sum:
                            sbQuery.AppendFormat("SELECT SUM({0}) FROM master.JobManagerialCompetency {1}", column, parameters);
                            break;
                        case SQL.Function.Aggregate.Avg:
                            sbQuery.AppendFormat("SELECT AVG({0}) FROM master.JobManagerialCompetency {1}", column, parameters);
                            break;
                        default:
                            // do nothing 
                            break;
                    }

                    cmd.CommandText = sbQuery.ToString();
                    cmd.CommandType = CommandType.Text;
                    try
                    {
                        conn.Open();
                        _result = cmd.ExecuteScalar();
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open) conn.Close();
                    }
                }
            }
            return _result;
        }

        public List<JobManagerialCompetency> GetList(int pageSize, int currentPage, string sortName, string sortOrder,string parameters)
        {
            List<JobManagerialCompetency> tt = new List<JobManagerialCompetency>();
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    int startRow = ((currentPage - 1) * pageSize) + 1;
                    int endRow = (startRow + pageSize);

                    StringBuilder sbQuery = new StringBuilder();
                    sbQuery.AppendFormat(" WITH result_set AS ");
                    sbQuery.AppendFormat(" ( ");
                    sbQuery.AppendFormat("    SELECT ");
                    sbQuery.AppendFormat("      ROW_NUMBER() OVER (ORDER BY {0} {1}) AS [row_number], ", sortName, sortOrder);
                    //sbQuery.AppendFormat("      A.JobManagerialID, A.Rowstatus, A.PositionID, A.CompetencyID, A.LevelCompetencyID, A.CreatedBy, A.CreatedDate, A.UpdatedBy, A.UpdatedDate,B.CompetncyDesc,C.PositionName,D.Level,E.DepartmentDesc ");
                    sbQuery.AppendFormat("A.PositionID ,C.PositionName ,E.DepartmentDesc");
                    sbQuery.AppendFormat("    FROM ");
                    sbQuery.AppendFormat("      master.JobManagerialCompetency A INNER JOIN master.Competency B ON A.CompetencyID = B.ComptID INNER JOIN master.Position C ON A.PositionID = C.PositionID INNER JOIN master.LevelCompetency D ON A.LevelCompetencyID = D.ID INNER JOIN master.Department E ON C.DepartmentID = E.DeptID ");
                    sbQuery.AppendFormat("      {0} ",parameters);
                    sbQuery.AppendFormat(" GROUP BY A.PositionID ,C.PositionName ,E.DepartmentDesc");
                    sbQuery.AppendFormat(" ) ");
                    sbQuery.AppendFormat(" SELECT * FROM result_set WHERE [row_number] BETWEEN {0} AND {1} ", startRow, endRow);

                    cmd.CommandText = sbQuery.ToString();
                    cmd.CommandType = CommandType.Text;
                    try
                    {
                        conn.Open();
                        using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                        {
                            while (dr.Read())
                            {
                                JobManagerialCompetency t = new JobManagerialCompetency(true);
                                //t.JobManagerialID = dr[JobManagerialCompetency.Fields.JobManagerialID] == DBNull.Value ? 0 : int.Parse(dr[JobManagerialCompetency.Fields.JobManagerialID].ToString());
                                //t.RowStatus = dr[JobManagerialCompetency.Fields.RowStatus] == DBNull.Value ? false : bool.Parse(dr[JobManagerialCompetency.Fields.RowStatus].ToString());
                                t.PositionID = dr[JobManagerialCompetency.Fields.PositionID] == DBNull.Value ? 0 : int.Parse(dr[JobManagerialCompetency.Fields.PositionID].ToString());
                                //t.CompetencyID = dr[JobManagerialCompetency.Fields.CompetencyID] == DBNull.Value ? 0 : int.Parse(dr[JobManagerialCompetency.Fields.CompetencyID].ToString());
                               // t.LevelCompetencyID = dr[JobManagerialCompetency.Fields.LevelCompetencyID] == DBNull.Value ? 0 : int.Parse(dr[JobManagerialCompetency.Fields.LevelCompetencyID].ToString());
                                //t.CreatedBy = dr[JobManagerialCompetency.Fields.CreatedBy] == DBNull.Value ? string.Empty : dr[JobManagerialCompetency.Fields.CreatedBy].ToString();
                                //t.CreatedDate = dr[JobManagerialCompetency.Fields.CreatedDate] == DBNull.Value ? (DateTime?)null : DateTime.Parse(dr[JobManagerialCompetency.Fields.CreatedDate].ToString());
                                //t.UpdatedBy = dr[JobManagerialCompetency.Fields.UpdatedBy] == DBNull.Value ? string.Empty : dr[JobManagerialCompetency.Fields.UpdatedBy].ToString();
                                //t.UpdatedDate = dr[JobManagerialCompetency.Fields.UpdatedDate] == DBNull.Value ? (DateTime?)null : DateTime.Parse(dr[JobManagerialCompetency.Fields.UpdatedDate].ToString());

                                
                                //t.LevelCompetency.Level = dr[LevelCompetency.Fields.Level] == DBNull.Value ? (short?)null : short.Parse(dr[LevelCompetency.Fields.Level].ToString());
                                //t.Competency.CompetncyDesc = dr[Competency.Fields.CompetncyDesc] == DBNull.Value ? string.Empty : dr[Competency.Fields.CompetncyDesc].ToString();

                                t.Position = new Position(true);
                                t.Position.PositionName = dr[Position.Fields.PositionName] == DBNull.Value ? string.Empty : dr[Position.Fields.PositionName].ToString();
                                t.Position.Department.DepartmentDesc = dr[Department.Fields.DepartmentDesc] == DBNull.Value ? string.Empty : dr[Department.Fields.DepartmentDesc].ToString();

                                tt.Add(t);
                                t.Dispose();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open) conn.Close();
                    }
                }
            }
            return tt;
        }

        public List<JobManagerialCompetency> GetListByPositionID(int positionID,string GroupCompt)
        {
            List<JobManagerialCompetency> tt = new List<JobManagerialCompetency>();
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = @"SELECT A.JobManagerialID, A.RowStatus, A.PositionID, A.CompetencyID, A.LevelCompetencyID, A.CreatedBy, A.CreatedDate, A.UpdatedBy, A.UpdatedDate 
                                       FROM master.JobManagerialCompetency A INNER JOIN master.Competency B ON B.ComptID = A.CompetencyID WHERE A.PositionID = @PositionID AND B.GroupCompetency = @GroupCompetency";
                    cmd.Parameters.Add("@PositionID", SqlDbType.Int).Value = positionID;
                    cmd.Parameters.Add("@GroupCompetency", SqlDbType.VarChar).Value = GroupCompt;
                    cmd.CommandType = CommandType.Text;
                    try
                    {
                        conn.Open();
                        using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                        {
                            while (dr.Read())
                            {
                                JobManagerialCompetency t = new JobManagerialCompetency();
                                t.JobManagerialID = dr[JobManagerialCompetency.Fields.JobManagerialID] == DBNull.Value ? 0 : int.Parse(dr[JobManagerialCompetency.Fields.JobManagerialID].ToString());
                                t.RowStatus = dr[JobManagerialCompetency.Fields.RowStatus] == DBNull.Value ? false : bool.Parse(dr[JobManagerialCompetency.Fields.RowStatus].ToString());
                                t.PositionID = dr[JobManagerialCompetency.Fields.PositionID] == DBNull.Value ? 0 : int.Parse(dr[JobManagerialCompetency.Fields.PositionID].ToString());
                                t.CompetencyID = dr[JobManagerialCompetency.Fields.CompetencyID] == DBNull.Value ? 0 : int.Parse(dr[JobManagerialCompetency.Fields.CompetencyID].ToString());
                                t.LevelCompetencyID = dr[JobManagerialCompetency.Fields.LevelCompetencyID] == DBNull.Value ? (int?)null : int.Parse(dr[JobManagerialCompetency.Fields.LevelCompetencyID].ToString());
                                t.CreatedBy = dr[JobManagerialCompetency.Fields.CreatedBy] == DBNull.Value ? string.Empty : dr[JobManagerialCompetency.Fields.CreatedBy].ToString();
                                t.CreatedDate = dr[JobManagerialCompetency.Fields.CreatedDate] == DBNull.Value ? (DateTime?)null : DateTime.Parse(dr[JobManagerialCompetency.Fields.CreatedDate].ToString());
                                t.UpdatedBy = dr[JobManagerialCompetency.Fields.UpdatedBy] == DBNull.Value ? string.Empty : dr[JobManagerialCompetency.Fields.UpdatedBy].ToString();
                                t.UpdatedDate = dr[JobManagerialCompetency.Fields.UpdatedDate] == DBNull.Value ? (DateTime?)null : DateTime.Parse(dr[JobManagerialCompetency.Fields.UpdatedDate].ToString());
                                tt.Add(t);
                                t.Dispose();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open) conn.Close();
                    }
                }
            }
            return tt;
        }

        public List<JobManagerialCompetency> GetListByPositionID(int positionID, string GroupCompt,int programID)
        {
            List<JobManagerialCompetency> tt = new List<JobManagerialCompetency>();
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = @"SELECT A.JobManagerialID, A.RowStatus, A.PositionID, A.CompetencyID, A.LevelCompetencyID, A.CreatedBy, A.CreatedDate, A.UpdatedBy, A.UpdatedDate 
                                       FROM master.JobManagerialCompetency A INNER JOIN master.Competency B ON B.ComptID = A.CompetencyID WHERE A.PositionID = @PositionID AND B.GroupCompetency = @GroupCompetency AND A.ProgramID =@ProgramID";
                    cmd.Parameters.Add("@PositionID", SqlDbType.Int).Value = positionID;
                    cmd.Parameters.Add("@GroupCompetency", SqlDbType.VarChar).Value = GroupCompt;
                    cmd.Parameters.Add("@ProgramID", SqlDbType.Int).Value = programID;
                    cmd.CommandType = CommandType.Text;
                    try
                    {
                        conn.Open();
                        using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                        {
                            while (dr.Read())
                            {
                                JobManagerialCompetency t = new JobManagerialCompetency();
                                t.JobManagerialID = dr[JobManagerialCompetency.Fields.JobManagerialID] == DBNull.Value ? 0 : int.Parse(dr[JobManagerialCompetency.Fields.JobManagerialID].ToString());
                                t.RowStatus = dr[JobManagerialCompetency.Fields.RowStatus] == DBNull.Value ? false : bool.Parse(dr[JobManagerialCompetency.Fields.RowStatus].ToString());
                                t.PositionID = dr[JobManagerialCompetency.Fields.PositionID] == DBNull.Value ? 0 : int.Parse(dr[JobManagerialCompetency.Fields.PositionID].ToString());
                                t.CompetencyID = dr[JobManagerialCompetency.Fields.CompetencyID] == DBNull.Value ? 0 : int.Parse(dr[JobManagerialCompetency.Fields.CompetencyID].ToString());
                                t.LevelCompetencyID = dr[JobManagerialCompetency.Fields.LevelCompetencyID] == DBNull.Value ? (int?)null : int.Parse(dr[JobManagerialCompetency.Fields.LevelCompetencyID].ToString());
                                t.CreatedBy = dr[JobManagerialCompetency.Fields.CreatedBy] == DBNull.Value ? string.Empty : dr[JobManagerialCompetency.Fields.CreatedBy].ToString();
                                t.CreatedDate = dr[JobManagerialCompetency.Fields.CreatedDate] == DBNull.Value ? (DateTime?)null : DateTime.Parse(dr[JobManagerialCompetency.Fields.CreatedDate].ToString());
                                t.UpdatedBy = dr[JobManagerialCompetency.Fields.UpdatedBy] == DBNull.Value ? string.Empty : dr[JobManagerialCompetency.Fields.UpdatedBy].ToString();
                                t.UpdatedDate = dr[JobManagerialCompetency.Fields.UpdatedDate] == DBNull.Value ? (DateTime?)null : DateTime.Parse(dr[JobManagerialCompetency.Fields.UpdatedDate].ToString());
                                tt.Add(t);
                                t.Dispose();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open) conn.Close();
                    }
                }
            }
            return tt;
        }

        public List<JobManagerialCompetency> GetListByPositionID(int positionID,  int programID)
        {
            List<JobManagerialCompetency> tt = new List<JobManagerialCompetency>();
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = @"SELECT A.JobManagerialID, A.RowStatus, A.PositionID, A.CompetencyID, A.LevelCompetencyID, A.CreatedBy, A.CreatedDate, A.UpdatedBy, A.UpdatedDate 
                                       FROM master.JobManagerialCompetency A  WHERE A.PositionID = @PositionID AND  A.ProgramID =@ProgramID";
                    cmd.Parameters.Add("@PositionID", SqlDbType.Int).Value = positionID;
                    cmd.Parameters.Add("@ProgramID", SqlDbType.Int).Value = programID;
                    cmd.CommandType = CommandType.Text;
                    try
                    {
                        conn.Open();
                        using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                        {
                            while (dr.Read())
                            {
                                JobManagerialCompetency t = new JobManagerialCompetency();
                                t.JobManagerialID = dr[JobManagerialCompetency.Fields.JobManagerialID] == DBNull.Value ? 0 : int.Parse(dr[JobManagerialCompetency.Fields.JobManagerialID].ToString());
                                t.RowStatus = dr[JobManagerialCompetency.Fields.RowStatus] == DBNull.Value ? false : bool.Parse(dr[JobManagerialCompetency.Fields.RowStatus].ToString());
                                t.PositionID = dr[JobManagerialCompetency.Fields.PositionID] == DBNull.Value ? 0 : int.Parse(dr[JobManagerialCompetency.Fields.PositionID].ToString());
                                t.CompetencyID = dr[JobManagerialCompetency.Fields.CompetencyID] == DBNull.Value ? 0 : int.Parse(dr[JobManagerialCompetency.Fields.CompetencyID].ToString());
                                t.LevelCompetencyID = dr[JobManagerialCompetency.Fields.LevelCompetencyID] == DBNull.Value ? (int?)null : int.Parse(dr[JobManagerialCompetency.Fields.LevelCompetencyID].ToString());
                                t.CreatedBy = dr[JobManagerialCompetency.Fields.CreatedBy] == DBNull.Value ? string.Empty : dr[JobManagerialCompetency.Fields.CreatedBy].ToString();
                                t.CreatedDate = dr[JobManagerialCompetency.Fields.CreatedDate] == DBNull.Value ? (DateTime?)null : DateTime.Parse(dr[JobManagerialCompetency.Fields.CreatedDate].ToString());
                                t.UpdatedBy = dr[JobManagerialCompetency.Fields.UpdatedBy] == DBNull.Value ? string.Empty : dr[JobManagerialCompetency.Fields.UpdatedBy].ToString();
                                t.UpdatedDate = dr[JobManagerialCompetency.Fields.UpdatedDate] == DBNull.Value ? (DateTime?)null : DateTime.Parse(dr[JobManagerialCompetency.Fields.UpdatedDate].ToString());
                                tt.Add(t);
                                t.Dispose();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open) conn.Close();
                    }
                }
            }
            return tt;
        }

        public object SelectCountByPositionComptID(int positionID,int ComptID,int programID)
        {
            object _result = null;
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    StringBuilder sbQuery = new StringBuilder();

                    sbQuery.AppendFormat("SELECT COUNT(*) FROM master.JobManagerialCompetency WHERE PositionID= @PositionID AND CompetencyID=@CompetencyID AND ProgramID = @ProgramID");

                    cmd.Parameters.Add("@PositionID", SqlDbType.Int).Value = positionID;
                    cmd.Parameters.Add("@CompetencyID", SqlDbType.Int).Value = ComptID;
                    cmd.Parameters.Add("@ProgramID", SqlDbType.Int).Value = programID;
                    cmd.CommandText = sbQuery.ToString();
                    cmd.CommandType = CommandType.Text;
                    try
                    {
                        conn.Open();
                        _result = cmd.ExecuteScalar();
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open) conn.Close();
                    }
                }
            }
            return _result;
        }

        public bool Update(List<JobManagerialCompetency> domains)
        {
            bool result = false;
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                conn.Open();
                SqlTransaction txn = conn.BeginTransaction();
                try
                {
                    domains.ForEach(delegate(JobManagerialCompetency domain)
                    {
                        SqlCommand cmd = conn.CreateCommand();
                        cmd.CommandText = "UPDATE master.JobManagerialCompetency SET  LevelCompetencyID = @LevelCompetencyID, UpdatedBy = @UpdatedBy, UpdatedDate = @UpdatedDate WHERE PositionID = @PositionID AND ProgramID=@ProgramID AND CompetencyID=@CompetencyID";
                        cmd.CommandType = CommandType.Text;
                      
                        cmd.Parameters.Add("@PositionID", SqlDbType.Int).Value = domain.PositionID;
                        cmd.Parameters.Add("@CompetencyID", SqlDbType.Int).Value = domain.CompetencyID;
                        cmd.Parameters.Add("@LevelCompetencyID", SqlDbType.Int).Value = (object)domain.LevelCompetencyID ?? DBNull.Value;
                        cmd.Parameters.Add("@ProgramID", SqlDbType.Int).Value = (object)domain.ProgramID ?? DBNull.Value;
                        cmd.Parameters.Add("@UpdatedBy", SqlDbType.VarChar).Value = (object)domain.UpdatedBy ?? DBNull.Value;
                        cmd.Parameters.Add("@UpdatedDate", SqlDbType.DateTime).Value = (object)domain.UpdatedDate ?? DBNull.Value;

                        cmd.Transaction = txn;
                        cmd.ExecuteNonQuery();
                        cmd.Dispose();
                    });

                    result = true;
                    txn.Commit();
                }
                catch (Exception ex)
                {
                    txn.Rollback();
                    throw (ex);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open) conn.Close();
                }


            }
            return result;
        }




        //public bool Save(List<JobManagerialCompetency> list)
        //{
        //    bool result = false;

        //    using (SqlConnection conn = new SqlConnection(connectionString))
        //    {

        //        conn.Open();
        //        SqlTransaction txn = conn.BeginTransaction();
        //        try
        //        {
        //            foreach (JobManagerialCompetency domain in list)
        //            {
        //                string query = "INSERT INTO master.JobManagerialCompetency(RowStatus, PositionID, CompetencyID, LevelCompetencyID, ProgramID, CreatedBy, CreatedDate, UpdatedBy, UpdatedDate) VALUES(@RowStatus, @PositionID, @CompetencyID, @LevelCompetencyID, @ProgramID, @CreatedBy, @CreatedDate, @UpdatedBy, @UpdatedDate)";
        //                SqlCommand cmd = new SqlCommand(query, conn);
        //                cmd.CommandType = CommandType.Text;
        //                cmd.Parameters.Add("@RowStatus", SqlDbType.Bit).Value = domain.RowStatus;
        //                cmd.Parameters.Add("@PositionID", SqlDbType.Int).Value = domain.PositionID;
        //                cmd.Parameters.Add("@CompetencyID", SqlDbType.Int).Value = domain.CompetencyID;
        //                cmd.Parameters.Add("@LevelCompetencyID", SqlDbType.Int).Value = (object)domain.LevelCompetencyID ?? DBNull.Value;
        //                cmd.Parameters.Add("@ProgramID", SqlDbType.Int).Value = (object)domain.ProgramID ?? DBNull.Value;
        //                cmd.Parameters.Add("@CreatedBy", SqlDbType.VarChar).Value = (object)domain.CreatedBy ?? DBNull.Value;
        //                cmd.Parameters.Add("@CreatedDate", SqlDbType.DateTime).Value = (object)domain.CreatedDate ?? DBNull.Value;
        //                cmd.Parameters.Add("@UpdatedBy", SqlDbType.VarChar).Value = (object)domain.UpdatedBy ?? DBNull.Value;
        //                cmd.Parameters.Add("@UpdatedDate", SqlDbType.DateTime).Value = (object)domain.UpdatedDate ?? DBNull.Value;

        //                cmd.Transaction = txn;
        //                cmd.ExecuteNonQuery();
        //                cmd.Dispose();
        //            }

                   


        //            result = true;
        //            txn.Commit();

        //        }
        //        catch (Exception ex)
        //        {
        //            txn.Rollback();
        //            throw (ex);
        //        }
        //        finally
        //        {
        //            if (conn.State == ConnectionState.Open) conn.Close();
        //        }
        //    }

        //    return result;
        //}
    }
}
